package com.zjj.shiro;
import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.zjj.shiro.permission.MyCustomPermission;
import com.zjj.shiro.service.ShiroService;

/**
 * 
 * @author zjj
 */
public class MyShiroRealm extends AuthorizingRealm {
	
	public String getName() {
		return "MyShiroRealm";
	}
	
	@Autowired
	private ShiroService shiroService;

	/**
	 * 验证用户输入的账号和密码是否正确 - 认证
	 * 
	 * @param AuthenticationToken
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String account = (String) token.getPrincipal(); // 登录账号
		String passwordMD5 = new String((char[]) token.getCredentials()); // 密码
		String userId = null;
		try {
			userId = shiroService.login(account, passwordMD5);
		} catch (AuthenticationException e) {
			throw e;
		}
		// 身份认证成功
		ShiroAuthenticationInfo authenticationInfo = new ShiroAuthenticationInfo(userId, passwordMD5, getName());
		authenticationInfo.setAccount(account);
		return authenticationInfo;
	}

	/**
	 * 授权
	 * 
	 * @param principalCollection
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		String userId = (String) principalCollection.getPrimaryPrincipal();
		AuthorizationInfo authorizationInfo = setAuthorizationInfo(userId);
		return authorizationInfo;
	}

	/**
	 * 
	 * @param userId
	 * @return
	 */
	private AuthorizationInfo setAuthorizationInfo(String userId) {
		Set<String> roles = new HashSet<String>();
		roles = shiroService.getUserRoles(userId);
		
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		// 设置角色
		authorizationInfo.setRoles(roles);
		Set<String> availableResources = shiroService.getMenuButtonResources(roles);
		// 设置菜单权限、按钮权限
		authorizationInfo.addObjectPermission(new MyCustomPermission(availableResources));
		return authorizationInfo;
	}
}
